var depth,
    depthid,
    speciesname,
    speciesid,
    quantity,
    tags;

var lastSpeciesFound;

$(document).ready(function() {

    // hide edit and remove button at first load,
    // show this on edit mode only, otherwise show add button
    $("#edit-species").hide();

    // dont show delete button on new depth
    if (getParamValue(window.location.href, "depth") == 'new') {
        $("#delete-depth").hide();
    }

    prepareSpeciesAutoComplete();
    prepareTagAutoComplete();

    // form fields selectors
    depth = $("#observationdepth_observationdepth"),
    depthid = $("#observationdepthdetail_observationdepthid"),
    speciesname = $('#species_species'),
    speciesid = $('#species_id'),
    quantity = $('#observationdepthdetail_quantity'),
    unit = $('#unit_unit'),
    tags = $('#observationdepthdetail_tag'),
    oddid = $('#observationdepthdetail_id'),
    allfields = $([]).add(speciesname).add(speciesid).add(quantity).add(tags);

    // save species into list
    $("#save-species").button().click(function(){
        allfields.removeClass( "ui-state-error" );
        depth.removeClass( "ui-state-error" );

        var formObj = createObjectForm();
        var success = saveSpecies(formObj, 'add');   // implemented in _speciesList

        if (success)
            allfields.val( "" ).removeClass( "ui-state-error" );
    });

    // edit a row
    $("#edit-species").button().click(function(){
        processEdit();
    });

    // clear fields
    $("#clear-form").button().click(function(){
        clearForm();
    });

    // delete this depth
    $("#delete-depth").button({
        icons: {primary: "ui-icon-close"}, text: false
    }).click(function(){
        window.location = "/data/deleteDepth/obs/" +
            getParamValue(window.location.href, "obs") + "/" +
            "depth/" + getParamValue(window.location.href, "depth");
    });

    // only show button save on editing depth value
    if (depth.val() == "")  $("#update-depth").hide();

    // update depth handler
    $("#update-depth").button({
        icons: {primary: "ui-icon-pencil"}, text: false
    }).click(function(){
        if ($(this).attr('title') == "Edit depth") {

            // edit mode
            $(this).attr('title', 'Save');
            depth.attr('readonly', false);
            depth.css('border-color', '#96B7E9');
            depth.css('color', '#312E25');
            $(this).button('option', 'icons', {primary: 'ui-icon-disk'});
            $(this).attr('title', 'Save');
            
        } else {
            
            // update mode
            if (updateDepth()) {

            }
        }

        return false;
    });

    // add unit
    $("#add_unit").button({
        icons: {primary: "ui-icon-plus"}, text: false
    });

    // set depth field numeric only
    depth.numeric();
    quantity.numeric();

})

/**
* handler on click edit button
*/
function processEdit() {
    var formObj = createObjectForm();
    formObj.id = oddid.val();

    if (saveSpecies(formObj, 'edit')) {
        allfields.val( "" ).removeClass( "ui-state-error" );
        toggleButton('add');
    } else {
        
    }
}

/**
 * Handler on click clear button
 */
function clearForm() {
    allfields.val( "" ).add(depth).add($('#validate-tip')).removeClass( "ui-state-error" );
    $('#validate-tip').text("");
    $('#validate-tip').hide();
    unit.clearOptions();
    toggleButton('add');
}

//function editSpeciesInput() {
//    speciesname.removeClass('ui-widget-readonly');
//    speciesname.attr('readonly', false);
//    speciesname.css('border-color', '#96B7E9');
//    speciesid.val("");
//}

function validateSpecies(speciesname) {
    if (lastSpeciesFound == "") {
        speciesid.val("");
        $("#valid_sp_msg").show();
        $("#valid_sp_msg").html('Unknown species "' + speciesname + '"');
        return false;
    }

    return true;
}

var cache = {};
function prepareSpeciesAutoComplete() {

    $("#species_species").autocomplete({
        delay: 100,
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response(cache[term]);
                return;
            }

            lastXhr = $.ajax({
                type: "GET",
                url: "/data/searchSpecies",
                data: {
                    term: term,
                    maxRows: 10
                },
                dataType: "json",
                success: function(data, textStatus, jqXHR){

                    cache[ term ] = data;

                    if (data.length == 0) {
                        lastSpeciesFound = "";
                    } else lastSpeciesFound = data[0].label;
                    
                    if (data.length == 1 && data[0].label == term) {
                        // if found exact species name, do not add "Add <>"
                    } else {
                        // add item "Add <species name>"
                        var newItem = new Object;
                        newItem.label = 'Add "' + term + '"';
                        newItem.value = term;
                        newItem.id = "new";
                        data.push(newItem);
                    }
                    
                    response( data );
                    
                    return false;
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("error: " + textStatus + ", " + errorThrown);
                    return false;
                }
            });
        },
        select: function(event, ui) {
            // add new species
            if  (ui.item.id == "new") {
                showNewSpeciesForm(ui.item.value);
            }
            else if (ui.item != null) {
                // set species name readonly
//                speciesname.attr('readonly', true);
//                speciesname.css('border-color', '#DDDDDD');
                speciesid.val(ui.item.id);

                // enable edit species button
//                $("#edit-species-input").show();

                // load possible units for the selected species, only if
                // selected species changed
                if (speciesname.val() != ui.item.value)
                    prepareUnits(ui.item.value, null);

                // clear species input message
                $("#valid_sp_msg").hide();
                $("#valid_sp_msg").html("");
            }
        }
    });
}

function showNewSpeciesForm(species) {
    var dialog = $("<div id='new_sp_form'></div>")
        .html("<input type='text' id='new_species' value='"+ species +"' class='ui-widget ui-widget-content ui-corner-all'>")
        .dialog({
            autoOpen: false,
            title: "Add new species",
            buttons: {
                "Save": function() {
                    insertNewSpecies($("#new_species").val());
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
    dialog.dialog("open");
}

function insertNewSpecies(species) {
    $.post('/data/createSpecies', {data: species},
        function(data) {

            if (data) {
                // hide dialog box
                $("#new_sp_form").parents('.ui-dialog').remove();
                $("#new_sp_form").remove();

                // after success inserting new species
                // set species name, set possible units for it
                lastSpeciesFound = species;
                speciesname.val(species);
                speciesid.val(data);
                prepareUnits(species, null);

                // empty autocomplete cache
                cache = {};

                // clear species input message
                $("#valid_sp_msg").hide();
                $("#valid_sp_msg").html("");
            } else {
                $("#new_sp_form").append('<div id="new_sp_msg" class="ui-widget ui-state-error-text">Species already exists.</div>');
            }
            
        },
        'html');
}

function prepareUnits(speciesname, selected) {
    $.ajax({
        type: 'get',
        url: $("#species-form").attr('action') + 'getObjectUnit/name/' + speciesname + '/type/species',
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
            if (data=="") {
                loadExtendedUnits('all', 'Individual(s)');
                return false;
            }

            $('#unit_unit').clearOptions();
            $('#unit_unit').buildOptions(data, selected);
            $('#unit_unit').append("<option value = 'all'>Show all units</option>");

            return true;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });
}

function prepareTagAutoComplete() {
    $("#observationdepthdetail_tag")
        .bind("keydown", function(event) {
            if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function(request, response) {
                $.getJSON("/data/searchTag", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function(){
                // custom minLength
                var term = extractLast( this.value );
//                if ( term.length < 2 ) {
//                        return false;
//                }
            },
            focus: function() {
                    // prevent value inserted on focus
                    return false;
            },
            select: function( event, ui ) {
                    var terms = split( this.value );
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push( "" );
                    this.value = terms.join( ", " );
                    return false;
            }

        });
}

function split( val ) {
    return val.split( /,\s*/ );
}
function extractLast( term ) {
    return split( term ).pop();
}

function createObjectForm(){
    var formObj = new Object;
    formObj.depthid = depthid.val();
    formObj.depth = depth.val();
    formObj.speciesid = speciesid.val();
    formObj.speciesname = speciesname.val();
    formObj.quantity = quantity.val();
//        formObj.unit = unit.val();
    $('#unit_unit option:selected').each(function(){
        formObj.unit = $(this).text();
        formObj.unitid = $(this).val();
    })
    formObj.tags = tags.val();
    formObj.obsid = getParamValue(window.location.href, "obs");

    return formObj;
}

function editForm(id){

    if (id == '') return;

    // populate fields value
    speciesid.val($("#odd_speciesid_"+id).html());
    speciesname.val($("#odd_name_"+id).html());
    quantity.val($("#odd_qt_"+id).html());
    prepareUnits(speciesname.val(), $("#odd_unit_"+id).html());
    tags.val($("#odd_tags_"+id).html());
    oddid.val(id);

    // set species name readonly
//    speciesname.attr('readonly', false);
//    speciesname.css('border-color', '#96B7E9');

    // enable edit species button
//    $("#edit-species-input").show();

    toggleButton('edit');
}

function toggleButton(method){
    if (method == 'add') {
        $("#edit-species").hide();
        $("#save-species").show();
    } else { //edit mode
        $("#edit-species").show();
        $("#save-species").hide();
    }
}

function updateDepth() {

    if (depth.val() == "") {
        depth.addClass('ui-state-error');
        return false;
    }
    depth.removeClass('ui-state-error');

    $.ajax({
        type: 'post',
        url: "/data/updateDepth",
        data: {depthForm: $("#species-form").serializeArray()},
        dataType: "html",
        success: function(data, textStatus, jqXHR) {
            location.reload(true);
            return false;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });

//        alert('saved');

    return true;
}
